package com.fred.util

import com.fred.xlog.Log
import java.io.*
import java.util.*

object PropertiesUtil {

    fun getProperties(fileName:String,key: String): String? {
        try {
//            val rb = ResourceBundle
//                .getBundle("config")
//            println("fb:${rb.getString(key)}")
//            return rb.getString(key)
            val properties = Properties()
            val filePath: String = getPropertiesPath(fileName)
//            println("filePath:${filePath}")
            val inputStream: InputStream = FileInputStream(File(filePath))
            properties.load(inputStream)
            return properties.getProperty(key)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun setProperties(fileName:String,key: String, value: String) {
        var output: OutputStream? = null
        try {
            val properties = Properties()
            properties.setProperty(key, value)
            val outFile = File(getPropertiesPath(fileName))
            if (!outFile.exists()) {
                outFile.createNewFile()
            }
            output = FileOutputStream(outFile)
            properties.store(output, null)
            output.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (output != null) {
                try {
                    output.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }


    private fun getPropertiesPath(fileName:String): String {
        val outFile = File(Util.propertiesPath,"${fileName}.properties")
        if (!outFile.exists()){
            if (!outFile.parentFile.exists()){
                outFile.parentFile.mkdirs()
            }
            outFile.createNewFile()
        }
        Log.i("fred","propertiesPath:${outFile.absolutePath}")
        return outFile.absolutePath
    }
}